import Vue from 'vue'
import Router from 'vue-router'
import Container from '@/components/container'
import Product from '@/components/container/product'
import Login from '@/components/login'
import cookie from "js-cookie"

Vue.use(Router)

const router = new Router({
  routes: [{
      path: '/',
      name: 'Index',
      redirect: "/login"
    },
    {
      path: '/login',
      name: 'Login',
      component: Login
    },
    {
      path: '/container',
      name: 'Container',
      component: Container,
      children: [{
        path: '/container/product',
        name: "Product",
        component: Product
      }]
    }
  ]
})

router.beforeEach((to, from, next) => {
  let token = cookie.get("token");

  if (to.path === "/login") { // 登陆页，若登陆直接跳转到商品页
    if (token !== null && token !== undefined) {
      next({
        name: 'Product'
      });
    } else {
      next();
    }
  } else { // 非登陆页，进行登陆拦截
    if (token !== null && token !== undefined) {
      next();
    } else {
      next({
        name: 'Login'
      });
    }
  }
})

export default router;
